package com.lemonfish.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.vo.JsonResult;
import com.lemonfish.enumcode.CodeEnum;
import com.lemonfish.pojo.entity.Permission;
import com.lemonfish.pojo.entity.Role;
import com.lemonfish.pojo.entity.RolePermission;
import com.lemonfish.pojo.vo.RoleVO;
import com.lemonfish.service.PermissionService;
import com.lemonfish.service.RolePermissionService;
import com.lemonfish.service.RoleService;
import com.lemonfish.util.MyJsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色 相关Controller
 *
 * @author Lemonfish
 * @version 1.0
 * @date 2020-03-02
 * Copyright © ï¿½Å³ï¿½
 */
@Api(tags = {"角色"})
@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController extends BaseCrudMappingRestController<Role, RoleVO> {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rpService;

    @GetMapping("/show")
    public MyJsonResult getList() {
        List<RoleVO> list = roleService.getViewObjectList(null, null, RoleVO.class);
        list.forEach(role -> role.setPermissionList(BeanUtils.buildTree(role.getPermissionList())));
        return MyJsonResult.success(list);
    }

    @GetMapping("/onlyRole")
    public MyJsonResult getOnlyRole() {
        List<Role> entityList = roleService.getEntityList(null);
        return MyJsonResult.success(entityList);
    }

    @DeleteMapping("/{roleId}/rights/{rightId}")
    public MyJsonResult deleteRight(@PathVariable("roleId") long roleId,
                                    @PathVariable("rightId") long rightId
    ) {
        int res = roleService.deleteRight(roleId, rightId);
        /*为了让页面的table不重新渲染，所以把数据传过去*/
        RoleVO roleVO = roleService.getViewObject(roleId, RoleVO.class);

        List<Permission> list = BeanUtils.buildTree(roleVO.getPermissionList());

        return res == 1 ? MyJsonResult.success(list) : MyJsonResult.fail(CodeEnum.FAIL_OPERATION);
    }

    /**
     * 更新权限
     *
     * @param roleId
     * @param
     * @return
     */
    @PutMapping("/{roleId}/rights")
    @Transactional
    public MyJsonResult updatePermission(@PathVariable("roleId") Long roleId,
                                         @RequestBody List<Long> keys) {
        //先把获取的keyArray转换成List，以便后续条件选择器使用
//        List<Long> keys = Arrays.asList(keyArray);
        // 如果size是0则return 错误消息
        if (keys.size() == 0) {
            return MyJsonResult.fail(CodeEnum.FAIL_INVALID_PARAM);
        }

        // 删除not in
        LambdaQueryWrapper<RolePermission> dqw = new LambdaQueryWrapper<>();
        dqw.notIn(RolePermission::getPermissionId, keys);
        dqw.eq(RolePermission::getRoleId, roleId);
        // 逻辑删除
        rpService.deleteEntities(dqw);
        //获取 List<RolePermission> 为了增加或者更新使用，需要循环找到主键
        List<RolePermission> rpList = keys.stream().map(item -> {
            LambdaQueryWrapper<RolePermission> lqw = new LambdaQueryWrapper<>();
            lqw.eq(RolePermission::getRoleId, roleId);
            lqw.eq(RolePermission::getPermissionId, item);
            // 这步判断是否被逻辑删除很关键,防止出现多个
            lqw.eq(RolePermission::getIsDeleted, 0);
            RolePermission flag = rpService.selectOne(lqw);

            return flag == null ? new RolePermission(roleId, item) : flag;
        }).collect(Collectors.toList());

        // 更新或者添加
        rpService.createOrUpdateEntities(rpList);


        return MyJsonResult.success(null);
    }

    /**
     * 加载更多数据
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取关联数据映射关系")
    @GetMapping("/attachMore")
    public JsonResult attachMore(HttpServletRequest request, ModelMap modelMap) throws Exception {
        Wrapper wrapper = null;
        return new JsonResult(modelMap);
    }
}
